import { HOTP } from './hotp';
import { timeCode } from './utils/time-code';

type TotpConfig = {
  secret: string;
  digits: number;
  interval?: number;
};

/**
 * TOTP(K, TC) = Truncate(HMAC-SHA-1(K, TC))
 * @param config
 * @returns string
 */
const totp = (config: TotpConfig): HOTP => {
  const { secret, digits, interval } = config;
  let timeNow = new Date();
  const counter = timeCode(String(timeNow), interval);
  return new HOTP({ secret, counter, digits });
};

/**
 * 生成动态口令
 * @param config
 * @returns string
 */
export const getToken = (config: TotpConfig): string => {
  const { secret, digits, interval } = config;
  const otp = totp({ secret, digits, interval });
  return otp.generate();
};

/**
 * 校验动态口令
 * @param token string
 */
export const validate = (
  token: string,
  config: {
    secret: string;
    digits: number;
    interval?: number;
  }
): boolean => {
  const { secret, digits, interval } = config;
  const otp = totp({ secret, digits, interval });
  return otp.validate(token);
};
